const storage = require('../../utils/storage')

Page({
  data:{
    list:[],
    allChecked:false,
    totalCount:0,
    totalPrice:0
  },

  onShow(){
    this.setData({ list: storage.get() })
    this.calc()
  },

  /* 勾选单个 */
  onToggle(e){
    const {skuId} = e.detail
    const list = this.data.list.map(g=>{
      if(g.skuId === skuId) g.checked = !g.checked
      return g
    })
    this.setData({ list })
    storage.set(list)
    this.calc()
  },

  /* 步进器 */
  onStep(e){
      const { skuid, type } = e.currentTarget.dataset;
      const list = this.data.list.map(item => {
        if (item.skuId !== skuid) return item;
        let newNum = item.num;
        if (type === 'minus' && newNum > 1) newNum--;
        if (type === 'plus') newNum++;
        return { ...item, num: newNum };
      });
      this.setData({ list });
      storage.set(list);
      this.calc();
    },

  /* 删除 */
  onDelete(e){
      const { skuid } = e.currentTarget.dataset;
      const list = this.data.list.filter(item => item.skuId !== skuid);
      this.setData({ list });
      storage.set(list);
      this.calc();
    },

  /* 全选/取消全选 */
  onToggleAll(){
    const allChecked = !this.data.allChecked
    const list = this.data.list.map(g=>({...g, checked: allChecked}))
    this.setData({ list, allChecked })
    storage.set(list)
    this.calc()
  },

  /* 计算合计 */
  calc(){
    let totalCount = 0, totalPrice = 0
    const list = this.data.list
    list.forEach(g=>{
      if(g.checked){
        totalCount += g.num
        totalPrice += g.price * g.num
      }
    })
    const allChecked = list.length ? list.every(g=>g.checked) : false
    this.setData({ totalCount, totalPrice, allChecked })
  },

  /* 结算 */
  onPay(){
    const selected = this.data.list.filter(g=>g.checked)
    wx.navigateTo({
      url: '/pages/payment/payment',
    })
  },
  onLoad(){
  const mock = [
    {skuId:1, name:'iPhone 15', sku:'128G 午夜色', price:5999, num:1, checked:true, thumb:'https://dummyimage.com/200x200/333/fff&text=i15'},
    {skuId:2, name:'AirPods Pro', sku:'第二代', price:1899, num:2, checked:false, thumb:'https://dummyimage.com/200x200/333/fff&text=APP'}
  ]
  storage.set(mock)
}
})